package com.lance.answer.question_export;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.dto.Item;
import com.lance.answer.dto.QuestionDetailNew;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Question;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.question_answer.XjCourseInfo;
import com.lance.answer.util.HttpUtil;
import com.lance.answer.util.XinJiangUtil;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.Semaphore;

/**
 * 2021-10-26 获取一体化某个课程 换个新的URL
 */
public class GetSingleAnswersByTeacherJsonNewUrl {


    public static List<WebElement> findElementsByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<List<WebElement>>)
                d -> d.findElements(By.cssSelector(cssSelector))));
    }

    public static WebElement findElementByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<WebElement>)
                d -> d.findElement(By.cssSelector(cssSelector))));
    }

    public static void main(String[] args) throws Exception {

        WebDriver driver = Util.getDriver(null);
        String url = "https://xjskk.open.com.cn/teacherspace-auth/#/login";
        // 打开指定的网站
        driver.get(url);
        Thread.sleep(200);

        for (WebElement we : driver.findElements(By.className("el-input__inner"))) {
            if ("text".equals(we.getAttribute("type"))) {
                we.sendKeys(new String[]{"lijunj"});
            }
            if ("password".equals(we.getAttribute("type"))) {
                we.sendKeys(new String[]{"lijunj"});
            }
        }
        driver.findElement(By.cssSelector("button[class='el-button login-ruleForm-btn el-button--primary']")).click();

        // 进入课程观察员角色的页面

        findElementByCssSelector(driver, "div[title='课程观察员']", 20).click();

        Thread.sleep(5000);


        Set<Cookie> cookies = driver.manage().getCookies();
        String studentSpaceProfile = Util.getStudentSpaceProfile(cookies);
        String authorization = Util.getAuthorization(cookies);
        // 初始化头部
        Map<String, String> heads = XinJiangUtil.initHttpHeads(studentSpaceProfile, authorization);

        String cookie = Util.getCookie(cookies);


        //: https://xjskk.open.com.cn/api/teacher/teacher-space-service/courses?pageNumber=6&pageSize=20&status=0&semesterId=23



        int openCourseId = 32873;
        String subjectName = "简明新疆历史";


        driver.navigate().refresh();
        Thread.sleep(4000);
        cookies = driver.manage().getCookies();
        // 初始化头部
        cookie = Util.getCookie(cookies);

        driver.get("https://xjskk.open.com.cn/teacher/#/menu/mission?openCourseId=" + openCourseId);

        List<Question> questions = Lists.newArrayList();
        questions.clear();

        Semaphore semaphore = new Semaphore(1);
        Thread.sleep(5000);
        for (WebElement span : findElementsByCssSelector(driver, "span[class='menu-font hover-color2-primary']", 30)) {
            if (Strings.isNullOrEmpty(span.getText())) {
                continue;
            }
            if (!span.getText().startsWith("随堂测试")&&!span.getText().startsWith("测试")) {
                continue;
            }
            try {
                semaphore.acquire();
                span.click();
                Thread.sleep(2000);
                Util.switchToLast(driver);
//                Set<String> windowHandles = driver.getWindowHandles();
//                List<String> list = new LinkedList<>(windowHandles);
//                driver.switchTo().window(list.get(1));

                String cUrl = driver.getCurrentUrl();
                String papaerId = cUrl.substring(cUrl.indexOf("&paperId=") + 9);
                System.err.println("papaerId:"+papaerId);

                try {

                    Thread.sleep(5000);
                    String getUrl = "https://xjskk.open.com.cn/api/teacher/teacher-space-service/testPaper/getPaperById?testPaperId=" + papaerId;

                    System.err.println("getUrl:"+getUrl);
                    String questionDetails = HttpUtil.get(getUrl, cookie, heads);
                    System.err.println("questionDetails:" + questionDetails);

                    QuestionDetailNew questionDetail = JSONObject.parseObject(questionDetails, QuestionDetailNew.class);

                    QuestionDetailNew.ContentDTO contentDTO= questionDetail.getContent();

                    for (QuestionDetailNew.ContentDTO.ItemsDTO itemsDTO:contentDTO.getItems()) {
                        Question question = new Question();
                        question.setTitle(itemsDTO.getI2());
//                        if(null!=contentDTO.getI9() ){
//                            question.setScore(contentDTO.getI9() + 0.0);
//                        }
                        question.setScore(itemsDTO.getI9());
                        int i3 = itemsDTO.getI3()==null?888:itemsDTO.getI3();
                        question.setQuestionType(i3);


                        if (i3 <= 3) {
                            if (i3 == 1) {
                                question.setQuestionTypeDesc("单选题");
                            } else if (i3 == 2) {
                                question.setQuestionTypeDesc("多选题");
                            } else {
                                question.setQuestionTypeDesc("判断题");
                            }


                            List<Item> items = Lists.newArrayList();
                            question.setItems(items);
                            List<String> answers = itemsDTO.getI6();
                            for (String answer : answers) {
                                Item item = new Item(answer, "");
                                items.add(item);
                            }

                            // 正确的答案所在的位置
                            List<String> correctIndex = itemsDTO.getI7();
                            List<String> correctList = Lists.newArrayList();
                            for (String cIndex : correctIndex) {
                                int index = Integer.parseInt(cIndex);
                                if (i3 != 3) {
                                    correctList.add(answers.get(index));
                                } else {
//                                    if (answers.get(index).equals("0")) {
//                                        correctList.add("对");
//                                    }
//                                    if (answers.get(index).equals("1")) {
//                                        correctList.add("错");
//                                    }
                                    // 10-30
                                    if (correctIndex.get(0).equals("0")) {
                                        correctList.add("对");
                                    }
                                    if (correctIndex.get(0).equals("1")) {
                                        correctList.add("错");
                                    }
                                }
                            }
                            String[] correctArray = new String[]{};
                            correctArray = correctList.toArray(correctArray);
                            System.err.println("correctArray:" + JSON.toJSONString(correctArray));
                            question.setCorrectArray(correctArray);

                            System.err.println("????????????111:" + JSON.toJSONString(question.getCorrectArray()));
                        } else {
                            if (i3 == 4) {
                                question.setQuestionTypeDesc("填空题");
                            } else {
                                question.setQuestionTypeDesc("简答题");
                            }
                            // 正确的答案所在的位置
                            List<String> answers = itemsDTO.getI6();
                            String[] correctArray = new String[]{};
                            correctArray = answers.toArray(correctArray);
                            question.setCorrectArray(correctArray);
                        }

                        questions.add(question);

                        System.err.println("??????????????222:" + JSON.toJSONString(question.getCorrectArray()));
                    }
                    FileUtils.write(new File("D:\\新疆一体化1026new\\" + subjectName + "\\" + papaerId + ".json"), questionDetails);


                } catch (Exception e) {
                    e.printStackTrace();
                } finally {

                }


                Util.switchToFirst(driver);
                Thread.sleep(5000);
            } catch (Exception e) {

            } finally {
            //    Util.switchToLast(driver);
            //    driver.close();
                semaphore.release();
            }
        }

        Thread.sleep(5000);


        //   Collections.sort(questions);
        List<Map<String, Object>> answers = new ArrayList<>();
        for (Question question : questions) {
            String title = question.getTitle();
            title = Util.dealContent(title);
            Map<String, Object> answerMap = new HashMap<>();
            answerMap.put("questionType", question.getQuestionType());
            answerMap.put("answerType", "click");
            answerMap.put("questionTypeDesc", question.getQuestionTypeDesc());
            answerMap.put("questionTitle", DealJsonString.delHTMLTag(title));
            answerMap.put("questionCode", question.getQuestionCode());
            answerMap.put("items", question.getItems());
            answerMap.put("answers", question.getCorrectArray());
            System.err.println("question.getCorrectArray():" + JSON.toJSONString(question.getCorrectArray()));
            answerMap.put("score", question.getScore());
            answers.add(answerMap);
        }

        FileUtils.write(new File("D:\\新疆一体化1026new\\" + subjectName + "\\" + subjectName + ".json"), JSONObject.toJSONString(answers, SerializerFeature.PrettyFormat), "utf-8");

        Thread.sleep(1000);
        //   driver.close();
        //  Util.switchToFirst(driver);


        System.err.println("end........");
//        driver.quit();


    }


}
